package client;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import message.*;


public class Client {

	/**
	 * @param args
	 */
	
	private Socket m_Socket;
	private SocketAddress m_SocketAddress;
	private InetAddress m_IpAddress;
	private Message m_Message;
	private SendMessage m_SendMessage;
	private ReceiveMessage m_ReceiveMessage;
	
	boolean connect()
	{
		m_Socket = new Socket();

		try {
			m_IpAddress = InetAddress.getLocalHost();
			m_SocketAddress = new InetSocketAddress(m_IpAddress,3000);
			m_Socket.connect(m_SocketAddress, 30);
			System.out.println("connect");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	
	boolean sendMessageOpenService(String sLogin, String sPassword)
	{
		boolean bRet = false;
		m_Message = new MessageOpenService();
		((MessageOpenService) m_Message).setM_sLogin(sLogin);
		((MessageOpenService) m_Message).setM_sPassword(sPassword);

		try {
			m_SendMessage = new SendMessage( m_Socket.getOutputStream() );
			m_SendMessage.writeObject(m_Message);
			m_SendMessage.flush();
			System.out.println("SendMessage");
			bRet = true;
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bRet;
	}

	boolean ReceiveMessage()
	{
		boolean bRet = false;
		
		try {
			m_ReceiveMessage = new ReceiveMessage( m_Socket.getInputStream() );
			String sReponse = m_ReceiveMessage.readUTF();
			System.out.println(sReponse);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bRet;
	}

	public static void main(String[] args) throws UnknownHostException {
		// TODO Auto-generated method stub

		Client client = new Client();
		client.connect();
		try {
			client.sendMessageOpenService("stephane", "ftpsteph");
			client.ReceiveMessage();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
